<template>
  <div class="snippet-manager">
    <h2>代码片段管理工具</h2>
    <div class="new-snippet">
      <input v-model="newTitle" type="text" placeholder="片段标题">
      <textarea v-model="newCode" rows="4" placeholder="粘贴代码片段"></textarea>
      <button @click="addSnippet">添加片段</button>
    </div>
    <div class="snippet-list" v-if="snippets.length">
      <h3>已保存的代码片段</h3>
      <ul>
        <li v-for="(item, index) in snippets" :key="index">
          <h4>{{ item.title }}</h4>
          <pre>{{ item.code }}</pre>
          <button @click="deleteSnippet(index)">删除</button>
        </li>
      </ul>
    </div>
    <p v-else>还没有保存任何代码片段。</p>
  </div>
</template>

<script>
export default {
  name: "SnippetManager",
  data() {
    return {
      newTitle: "",
      newCode: "",
      snippets: []
    };
  },
  methods: {
    loadSnippets() {
      const stored = localStorage.getItem("snippets");
      this.snippets = stored ? JSON.parse(stored) : [];
    },
    saveSnippets() {
      localStorage.setItem("snippets", JSON.stringify(this.snippets));
    },
    addSnippet() {
      if (this.newTitle.trim() === "" || this.newCode.trim() === "") return;
      this.snippets.push({
        title: this.newTitle,
        code: this.newCode
      });
      this.newTitle = "";
      this.newCode = "";
      this.saveSnippets();
    },
    deleteSnippet(index) {
      this.snippets.splice(index, 1);
      this.saveSnippets();
    }
  },
  mounted() {
    this.loadSnippets();
  }
};
</script>

<style scoped>
.snippet-manager {
  max-width: 600px;
  margin: 20px auto;
  padding: 10px;
}
.new-snippet {
  margin-bottom: 20px;
}
.new-snippet input,
.new-snippet textarea {
  width: 100%;
  padding: 8px;
  margin-bottom: 10px;
  box-sizing: border-box;
}
button {
  padding: 8px 16px;
  background-color: #2ecc71;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #27ae60;
}
.snippet-list ul {
  list-style: none;
  padding: 0;
}
.snippet-list li {
  background: #ecf0f1;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 4px;
  position: relative;
}
.snippet-list pre {
  background: #bdc3c7;
  padding: 8px;
  border-radius: 4px;
  white-space: pre-wrap;
  margin-top: 5px;
}
.snippet-list button {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #e74c3c;
}
.snippet-list button:hover {
  background-color: #c0392b;
}
</style> 